#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "hi_io.h"
#include "hi_gpio.h"

#define KEY HI_IO_NAME_GPIO_14

uint8_t keyflag = 0;
hi_void gpio_callback(void)
{   
    keyflag++;
        
    if(keyflag>5)
    {
        keyflag = 0;
    }
    printf("flag=%d\r\n",keyflag);
}

void key_init(void)
{
    int ret;
    ret = hi_io_set_func(KEY, HI_IO_FUNC_GPIO_14_GPIO);        // 设置IO14为GPIO功能
    if (ret != 0)
    {
        printf("set gpio 14 failed.\n");
        return;
    }
    ret = hi_io_set_pull(KEY, HI_IO_PULL_UP);                  // 设置GPIO上拉
    if (ret != 0)
    {
        printf("set gpio 14 pull up failed.\n");
        return;
    }

    ret = hi_io_set_schmitt(KEY,HI_TRUE);                      //消除抖动
    if (ret != 0)
    {
        printf("set gpio 14 failed.\n");
        return;
    }

    ret = hi_gpio_init();                                      // GPIO初始化
    if (ret != 0)
    {
        printf("gpio init failed.\n");
        return;
    }

    ret = hi_gpio_set_dir(KEY, HI_GPIO_DIR_IN);                // 设置GPIO为输入模式
    if (ret != 0)
    {
        printf("set gpio 14 in failed.\n");
        return;
    }

    ret = hi_gpio_register_isr_function(KEY,                   // KEY按键引脚
                                  HI_INT_TYPE_EDGE,            // 下降沿检测
                                  HI_GPIO_EDGE_FALL_LEVEL_LOW, // 低电平时触发
                                  &gpio_callback,              // 触发后调用的回调函数
                                  NULL);                       // 回调函数的传参值
    if (ret != 0)
    {
        printf("register func failed.\n");
        return;
    }      

}